package io.renren.modules.api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import io.renren.modules.api.dao.UsertokenDao;
import io.renren.modules.api.entity.UsertokenEntity;
import io.renren.modules.api.service.UsertokenService;



/**
 * @author 杨帅
 */
@Service("usertokenService")
public class UsertokenServiceImpl implements UsertokenService {
	@Autowired
	private UsertokenDao usertokenDao;

	//12小时后过期
	private final static int EXPIRE = 3600 * 12;
	
	@Override
	public UsertokenEntity queryObject(String userinfoid){
		return usertokenDao.queryObject(userinfoid);
	}
	
	@Override
	public List<UsertokenEntity> queryList(Map<String, Object> map){
		return usertokenDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return usertokenDao.queryTotal(map);
	}
	
	@Override
	public void save(UsertokenEntity usertoken){
		usertokenDao.save(usertoken);
	}
	
	@Override
	public void update(UsertokenEntity usertoken){
		usertokenDao.update(usertoken);
	}
	
	@Override
	public void delete(String userinfoid){
		usertokenDao.delete(userinfoid);
	}
	
	@Override
	public void deleteBatch(String[] userinfoids){
		usertokenDao.deleteBatch(userinfoids);
	}

	@Override
	public UsertokenEntity queryByToken(String token) {
		return usertokenDao.queryByToken(token);
	}

	@Override
	public Map<String, Object> createToken(String userinfoId) {
		//生成一个token
		String token = UUID.randomUUID().toString().replaceAll("-","");
		//当前时间
		Date now = new Date();

		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		UsertokenEntity tokenEntity = usertokenDao.queryObject (userinfoId);
		if(tokenEntity == null){
			tokenEntity = new UsertokenEntity();
			tokenEntity.setUserinfoid(userinfoId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdatedate(now);
			tokenEntity.setExpiredate(expireTime);

			//保存token
			save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdatedate(now);
			tokenEntity.setExpiredate(expireTime);

			//更新token
			update(tokenEntity);
		}

		Map<String, Object> map = new HashMap<>(16);
		map.put("token", token);
		map.put("expire", EXPIRE);

		return map;
	}

}
